package com.xebest.web.controller.restapi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.xebest.api.dto.*;
import com.xebest.api.dto.resdto.OrderInfoResDTO;
import com.xebest.api.service.ForErpOrderIApiService;
import com.xebest.common.base.controller.BaseController;
import com.xebest.common.base.pagedto.XePageInfoDto;
import com.xebest.common.enums.cms.SysCmsPagePlatEnum;
import com.xebest.common.enums.erp.order.VenOrderStatusEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreTmsStatusEnum;
import com.xebest.common.enums.logtype.ErpLogTypeEnum;
import com.xebest.common.util.XeBaseUtil;
import com.xebest.config.ParamConfig;
import com.xebest.config.SendGoodOrderSender;
import com.xebest.constant.XeConstans;
import com.xebest.constant.XeErrorCode;
import com.xebest.util.XeVenBusConstans;
import com.xebest.web.form.XeVenOrderForm;
import com.xebest.web.form.XeVenSplitOrderDetailForm;
import com.xebest.web.form.XeVenSplitOrderForm;
import com.xebest.web.model.WeChatSupplierOrderEntity;
import com.xebest.web.model.WeChatSupplierOrdersEntity;
import com.xebest.web.model.XeVenExpHandleEntity;
import com.xebest.web.service.WeChatSupplierService;
import com.xebest.web.service.XeVenExpHandleService;
import com.xebest.web.service.XeVenOrderService;
import com.xebest.web.service.XeVenSendGoodsService;
import com.xebest.web.view.ErpUserInfo;
import com.xebest.web.view.XeVenOrderDetailView;
import com.xebest.web.view.XeVenOrderView;
import com.xebest.web.view.XeVenSendView;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;


/**
 * 此类为微信供应商提供
 *
 * @author ruancz
 */
@RestController
@RequestMapping("restapi/weChatSupplier")
public class WeChatSupplierRestApi extends BaseController {
    //日志记录类
    private static final Logger log = LoggerFactory.getLogger(WeChatSupplierRestApi.class);

    @Autowired
    private WeChatSupplierService weChatSupplierService;
    @Autowired
    private ParamConfig paramConfig;//获取公共配置信息
    @Autowired
    private XeVenSendGoodsService xeVenSendGoodsService;//发货业务处理
    @Autowired
    private XeVenOrderService xeVenOrderService;
    @Autowired
    private ForErpOrderIApiService forErpOrderIApiService; //发货订单同步业务
    @Autowired
    private XeVenExpHandleService xeVenExpHandleService;//异常补偿业务

    /**
     * 供应商查询订单列表
     *
     * @author ruancz
     */
    @RequestMapping("/queryOrderList")
    public WechatSupplierPageDTO queryOrderList(@RequestBody WeChatSupplierQueryDTO form) {
        log.info("供应商查询订单列表入参: {}", JSON.toJSONString(form));
        WechatSupplierPageDTO pageDTO = new WechatSupplierPageDTO();
        if (null == form || StringUtils.isBlank(form.getUserCode())) {
            pageDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
            return pageDTO;
        }
        try {
            PageHelper.startPage(form.getPageNum(), form.getPageSize(), true);
            List<WeChatSupplierOrdersEntity> actionList = this.weChatSupplierService.queryOrderList(form);
            List<WeChatSupplierOrdersEntityDTO> resultList = JSONArray.parseArray(JSONArray.toJSONString(actionList),
                    WeChatSupplierOrdersEntityDTO.class);
            XePageInfoDto pageInfo = new XePageInfoDto<>(actionList);
            pageDTO.setXePageInfoDto(pageInfo);
            pageDTO.setActionList(resultList);
            pageDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);
            pageDTO.setPicServer(paramConfig.getImgUrl() + XeConstans.MOBILE_PRO_IMG_URL);
        } catch (Exception e) {
            log.error("供应商查询订单列表接口异常：{}", e);
            pageDTO.setStatus(XeErrorCode.PORJECT_ERROR);
        }
        return pageDTO;
    }

    /**
     * 供应商查询订单详情
     *
     * @author ruancz
     */
    @RequestMapping("/queryOrderDetail")
    public WechatSupplierPageDTO queryOrderDetail(@RequestBody WeChatSupplierQueryDTO form) {
        log.info("供应商查询订单详情入参: {}", JSON.toJSONString(form));
        WechatSupplierPageDTO pageDTO = new WechatSupplierPageDTO();
        if (null == form || StringUtils.isBlank(form.getUserCode()) || StringUtils.isBlank(form.getOrderId())) {
            pageDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
            return pageDTO;
        }
        try {
            WeChatSupplierOrderEntity orderEntity = this.weChatSupplierService.queryOrderDetail(form);
            if (orderEntity == null) {
                pageDTO.setOrderEntity(null);
            } else {
                String orderEntityJson = JSON.toJSONString(orderEntity);
                WeChatSupplierOrderDTO orderDTO = JSON.parseObject(orderEntityJson, WeChatSupplierOrderDTO.class);
                pageDTO.setOrderEntity(orderDTO);
            }
            pageDTO.setPicServer(paramConfig.getImgUrl() + XeConstans.MOBILE_PRO_IMG_URL);
            pageDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);
        } catch (Exception e) {
            pageDTO.setStatus(XeErrorCode.PORJECT_ERROR);
            log.error("供应商查询订单详情接口异常：{}", e);
        }
        return pageDTO;
    }

    /**
     * 供应商查询物流
     *
     * @author ruancz
     */
    @RequestMapping("/queryOrderlogistics")
    public WeChatSupplierOrderLogisticsDTO queryOrderlogistics(@RequestBody WeChatSupplierQueryDTO form) {
        log.info("供应商查询物流入参:{}", JSON.toJSONString(form));
        WeChatSupplierOrderLogisticsDTO dto = new WeChatSupplierOrderLogisticsDTO();
        if (null == form || StringUtils.isBlank(form.getUserCode()) || StringUtils.isBlank(form.getOrderId())) {
            dto.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
            return dto;
        }
        try {
            dto = this.weChatSupplierService.queryOrderlogistics(form);
            dto.setStatus(XeErrorCode.PORJECT_SUCCESS);
        } catch (Exception e) {
            dto.setStatus(XeErrorCode.PORJECT_ERROR);
            log.error("供应商查询物流接口异常：{}", e);
        }
        return dto;
    }

    /**
     * 查询个人中心
     *
     * @author ruancz
     */
    @RequestMapping("/queryPersonalCenter")
    public WeChatSupplierCentorDto queryPersonalCenter(@RequestBody WeChatSupplierQueryDTO form) {
        log.info("供应商查询个人中心: {}", JSON.toJSONString(form));
        WeChatSupplierCentorDto dto = new WeChatSupplierCentorDto();
        if (null == form || StringUtils.isBlank(form.getUserCode())) {
            dto.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
            return dto;
        }
        try {
            dto = this.weChatSupplierService.queryPersonalCenter(form);
            dto.setStatus(XeErrorCode.PORJECT_SUCCESS);
        } catch (Exception e) {
            log.error("供应商查询个人中心接口异常：{}", e);
            dto.setStatus(XeErrorCode.PORJECT_ERROR);
        }
        return dto;
    }

    /**
     * 查询待发货订单数
     *
     * @author guosen
     */
    @RequestMapping("/queryWaitDelivery")
    public WeChatSupplierCentorDto queryWaitDelivery(@RequestBody WeChatSupplierQueryDTO form) {
        log.info("查询待发货订单数:{}", JSON.toJSONString(form));
        WeChatSupplierCentorDto dto = new WeChatSupplierCentorDto();
        if (null == form || StringUtils.isBlank(form.getUserCode())) {
            dto.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
            return dto;
        }
        try {
            dto = this.weChatSupplierService.queryWaitDelivery(form);
            dto.setStatus(XeErrorCode.PORJECT_SUCCESS);

        } catch (Exception e) {
            log.error("查询待发货订单数异常：{}", e);
            dto.setStatus(XeErrorCode.PORJECT_ERROR);
        }
        return dto;
    }

    /**
     * 查询订单明细接口
     *
     * @author zhouys
     * @see com.xebest.web.controller.order.XeVenOrderController#queryOrderInfoDetail
     */
    @RequestMapping("queryOrderInfoDetail")
    public WeChatOrderSendResponseDto queryOrderInfoDetail(@RequestBody WeChatOrderSendDto form) {
        WeChatOrderSendResponseDto responseDto = new WeChatOrderSendResponseDto();
        log.info("查询订单明细接口请求参数为：{}", JSON.toJSONString(form));
        //验证必要参数
        if (StringUtils.isBlank(form.getOrderId())) {
            responseDto.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
            return responseDto;
        }
        ErpUserInfo userInfo = new ErpUserInfo();
        userInfo.setUserCode(form.getUserCode());
        try {
            //返回结果
            Map<String, Object> resultMap = this.xeVenOrderService.queryOrderInfoDetail(form.getOrderId(), userInfo);
            resultMap.put("picServer", paramConfig.getImgUrl() + XeConstans.ERP_PRO_PIC_DIR); //图片服务器地址
            responseDto.setResultMap(resultMap);
            responseDto.setStatus(XeErrorCode.PORJECT_SUCCESS);
            return responseDto;
        } catch (Exception e) {
            log.error("查询订单明细接口异常：{}", e);
            responseDto.setStatus(XeErrorCode.PORJECT_ERROR);
            return responseDto;
        }
    }

    /**
     * 确认实发
     *
     * @author zhouys
     * @see com.xebest.web.controller.order.XeVenOrderController#updateOrderRealSendNum
     */
    @RequestMapping("/updateOrderRealSendNum")
    public WeChatOrderSendResponseDto updateOrderRealSendNum(@RequestBody WeChatOrderSendDto requestDto) {
        log.info("单条修改订单实发数量：{}", JSON.toJSONString(requestDto));
        WeChatOrderSendResponseDto responseDto = new WeChatOrderSendResponseDto();
        String orderId;
        if (null == requestDto || StringUtils.isBlank((orderId = requestDto.getOrderId()))) {
            responseDto.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
            responseDto.setMsg("缺少参数orderId");
            return responseDto;
        }
        ErpUserInfo userInfo = new ErpUserInfo();
        userInfo.setUserCode(requestDto.getUserCode());
        userInfo.setLoginName(requestDto.getLoginName());
        userInfo.setAdminFlag(XeConstans._XE_TWO);//默认给改店铺的系统管理员

        XeVenSplitOrderForm xeVenSplitOrderForm = new XeVenSplitOrderForm();
        xeVenSplitOrderForm.setOrderId(requestDto.getOrderId());//订单id
        XeVenOrderForm xeVenOrderForm = new XeVenOrderForm();
        xeVenOrderForm.setOrderId(orderId);
        List<XeVenOrderView> orderInfoList = xeVenOrderService.queryOrderInfoList(xeVenOrderForm, userInfo);
        if (orderInfoList == null || orderInfoList.size() != 1) {
            responseDto.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
            responseDto.setMsg("查询订单信息异常");
        }
        XeVenOrderView xeVenOrderView = orderInfoList.get(0);
        xeVenSplitOrderForm.setStoreId(xeVenOrderView.getStoreId());//仓库ID
        xeVenSplitOrderForm.setPayType(Integer.valueOf(xeVenOrderView.getPayType()));//支付类型
        xeVenSplitOrderForm.setConfirmSendNum(xeVenOrderView.getConfirmSendNum());
        //订单下的商品转换为接口需要的类型
        List<XeVenSplitOrderDetailForm> splitOrderDetailList = new ArrayList<>();
        List<Map<String, Object>> details = requestDto.getDetails();
        XeVenSplitOrderDetailForm detailForm;
        XeVenOrderDetailView detailView;
        for (Map<String, Object> detail : details) {
            detailView = JSONObject.parseObject(JSON.toJSONString(detail), XeVenOrderDetailView.class);
            detailForm = new XeVenSplitOrderDetailForm();
            detailForm.setProSku(detailView.getProSku());
            detailForm.setRealSendNum(detailView.getRealSendNum());
            detailForm.setItemId(detailView.getItemId());
            detailForm.setPurchaseNum(detailView.getPurchaseNum());
            splitOrderDetailList.add(detailForm);
        }
        xeVenSplitOrderForm.setSplitOrderDetailList(splitOrderDetailList);

        try {
            Map<String, Object> resultMap = xeVenOrderService.updateOrderSendNum(userInfo, xeVenSplitOrderForm, requestDto.getRequestIp(),SysCmsPagePlatEnum.MOBILE);
            Object code = resultMap.get(XeVenBusConstans.CODE);
            if (code.equals(XeVenBusConstans.BUSSINESS_SUCCESS)) {
                responseDto.setStatus(XeErrorCode.PORJECT_SUCCESS);
            } else {
                responseDto.setStatus(XeErrorCode.PORJECT_ERROR);
                Object msg = resultMap.get(XeVenBusConstans.MSG);
                responseDto.setMsg(msg.toString());
            }
            return responseDto;
        } catch (Exception e) {
            log.error("单条修改订单实发数量：{}", e);
            responseDto.setStatus(XeErrorCode.PORJECT_ERROR);
            responseDto.setMsg("修改订单实发数量异常");
            return responseDto;
        }
    }

    /**
     * 微信erp订单发货
     *
     * @author zhouys
     * @see com.xebest.web.controller.order.XeVenSendGoodsController#batchSend（参考 鲜易云ERP单个或者多个订单发货）
     */
    @RequestMapping("send")
    public WeChatOrderSendResponseDto send(@RequestBody WeChatOrderSendDto requestDto) {
        WeChatOrderSendResponseDto responseDTO = new WeChatOrderSendResponseDto();
        String requestIp=requestDto.getRequestIp();
        ErpUserInfo userInfo = new ErpUserInfo();
        userInfo.setUserCode(requestDto.getUserCode());
        userInfo.setLoginName(requestDto.getLoginName());
        //2、获取前台需要传入订单号
        List<String> orderIds = new ArrayList<>();//待发货订单容器
        orderIds.add(requestDto.getOrderId());//订单号
        log.info("订单发货入参：{}", JSONObject.toJSONString(orderIds));

        //3、用户登录信息
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userCode", userInfo.getUserCode());//商户编码
        paramMap.put("orderIds", orderIds);//待发货订单号
        //4、批量查询要处理的待发货订单
        List<XeVenSendView> waitSendList = xeVenSendGoodsService.queryWaitSendList(paramMap);
        log.info("批量查询要处理的待发货订单:{}", JSONObject.toJSONString(waitSendList));
        List<XeVenSendView> waitUpList = new ArrayList<>();
        //5、开始执行批量发货操作
        for (XeVenSendView sendView : waitSendList) {
            //判断发货状态是否为待发货 是否已经接入TMS
            if (VenStoreTmsStatusEnum.YES.getValue() == sendView.getTmsStatus()) {
                responseDTO.setStatus(XeErrorCode.PORJECT_ERROR);
                responseDTO.setMsg("已接入TMS");
                return responseDTO;
            }
            if (VenOrderStatusEnum.WAIT_SEND.getValue() != sendView.getOrderStatus()) {
                responseDTO.setStatus(XeErrorCode.PORJECT_ERROR);
                responseDTO.setMsg("订单不是代发货状态不能进行发货!");
                return responseDTO;
            }
            sendView.setCreaterUser(userInfo.getLoginName());//创建人
            sendView.setModfiyUser(userInfo.getLoginName());//修改人
            sendView.setSendTime(new Date());
            try {
                int sendResult = xeVenSendGoodsService.updateSend(sendView);//更新发货
                if (sendResult > 0) {
                    waitUpList.add(sendView);//添加待更新发货(商城订单使用)
                    //添加日志
                    xeVenOrderService.insertMqLog(ErpLogTypeEnum.erpOrderModifySend.getValue(), sendView.getOrderId(), SysCmsPagePlatEnum.MOBILE.getName()+"对订单【" + sendView.getOrderId() + "】进行发货操作", userInfo, requestIp, "发货");
                }
            } catch (Exception e) {
                log.error("订单发货错误信息:订单号{},发货执行异常{}!", sendView.getOrderId(), e);
                responseDTO.setStatus(XeErrorCode.PORJECT_ERROR);
                responseDTO.setMsg("订单发货异常");
                return responseDTO;
            }
        }
        //6、批量发货提示信息拼接
        //7、通知商城订单库已发货，同时算三方商户佣金
        int waitUpListSize = waitUpList.size();//需要通知的订单数量
        List<String> expOrderList = new ArrayList<>();//如果发货通知异常使用
        try {
            if (waitUpListSize > 0) {
                List<OrderInfoDTO> listDTO = new ArrayList<>();
                OrderInfoDTO paramDTO = new OrderInfoDTO();//商城同步参数
                for (XeVenSendView viewDTO : waitUpList) {
                    expOrderList.add(viewDTO.getOrderId());
                    OrderInfoDTO orderInfoDTO = new OrderInfoDTO();
                    orderInfoDTO.setVenType(viewDTO.getVenType());
                    orderInfoDTO.setOrderId(viewDTO.getOrderId());
                    orderInfoDTO.setSendTime(viewDTO.getSendTime());
                    orderInfoDTO.setOrderStatus(VenOrderStatusEnum.SEND.getValue());
                    orderInfoDTO.setUserCode(viewDTO.getUserCode());
                    orderInfoDTO.setOrderDetailList(JSON.parseArray(JSON.toJSONString(viewDTO.getOrderDetailList()), OrderInfoDetailDTO.class));
                    orderInfoDTO.setPayAmount(viewDTO.getEpayReceAmt() == null ? viewDTO.getPayAmount() : viewDTO.getEpayReceAmt());//应收金额
                    orderInfoDTO.setRealRefundedAmount(viewDTO.getDifferAmount());//退款总额
                    int i = 0;
                    for (OrderInfoDetailDTO detailDTO : orderInfoDTO.getOrderDetailList()) {
                        BigDecimal refundAmount = viewDTO.getOrderDetailList().get(i).getDifferenceAmount();
                        //v3.1.4 平台优惠金额 佣金计算需要加上 如果有实发，则根据实发数 计算平台优惠金额   商品明细 优惠=(优惠)*拆分数量/购买数量
                        BigDecimal platCpn = XeBaseUtil.baseUtil.calPlatCpnAmt(detailDTO.getPurchaseNum(), detailDTO.getRealSendNum(), detailDTO.getPlatPmtAmount());
                        BigDecimal sendAmt = XeBaseUtil.baseUtil.calSendAmt(detailDTO.getPurchaseNum(), detailDTO.getRealSendNum(), detailDTO.getProTotalPrice(), detailDTO.getPmtAmount());
                        log.info("商品sku{}，平台优惠券金额{}，发货金额{}", detailDTO.getProSku(), platCpn, sendAmt);
                        detailDTO.setProPayAmount(sendAmt);
                        detailDTO.setPlatPmtAmount(platCpn);
                        if (refundAmount != null) {
                            detailDTO.setRealRefundedAmount(refundAmount);//退款金额
                        } else {
                            detailDTO.setRealRefundedAmount(BigDecimal.ZERO);//退款金额
                        }
                        i++;
                    }
                    listDTO.add(orderInfoDTO);
                }
                paramDTO.setOrderInfoList(listDTO);
                log.info("发货通知前台入参 :{}", JSON.toJSONString(paramDTO));
                OrderInfoResDTO orderInfoResDTO = forErpOrderIApiService.erpConfirmOrder(paramDTO);
                log.info("发货通知前台出参 :{}", JSON.toJSONString(orderInfoResDTO));
                if (!orderInfoResDTO.getStatus().equals(XeErrorCode.PORJECT_SUCCESS)) {
                    XeVenExpHandleEntity entity = new XeVenExpHandleEntity();
                    entity.setExpType(2);
                    entity.setOrderJson(JSONObject.toJSONString(expOrderList));
                    entity.setExpMsg("正常发货通知异常：" + orderInfoResDTO.getMsg());
                    xeVenExpHandleService.insertXeVenExpHandle(entity);
                }
            }
        } catch (Exception e) {
            try {
                XeVenExpHandleEntity entity = new XeVenExpHandleEntity();
                entity.setExpType(2);
                entity.setOrderJson(JSONObject.toJSONString(expOrderList));
                entity.setExpMsg("正常发货通知异常：" + e.getMessage());
                xeVenExpHandleService.insertXeVenExpHandle(entity);
            } catch (Exception e1) {
                log.error("发货通知补偿业务执行异常{}!", e1);
            }
            log.error("订单发货通知前台错误信息:同步发货执行异常{}!", e);
        }
        //发送短信通知
        if (waitUpListSize > 0) {
            SendGoodOrderSender.sender.sendMessage(JSONObject.toJSONString(waitUpList));//消息通知
            log.info("发货通知消息成功!");
        }
        responseDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);
        responseDTO.setMsg("发货成功");
        //8、返回结果
        return responseDTO;
    }
}
